<!-- @format -->

<template>
	<div class="ma-content-block  p-4">
		<!-- <ma-city-linkage v-model="city" /> -->
		<!-- <button @click="handlechakan">地图选点</button> -->
		<!-- CRUD 组件 -->
		<ma-crud :options="options" :columns="columns" ref="crudRef">
			<template #dept_id="{ record }">
				<!-- 对标题加上 tag -->
				<a-tag color="blue">{{ record.dept.name }}</a-tag>
			</template>
			<template #annex="{ record }">
				<!-- 对标题加上 tag -->
				<div v-if="record.annex">
					<div v-for="(item, index) in record.annex"
						:key="index">
						<a-link
						
						:href="item"
						target="_blank"
						rel="noopener noreferrer"
						>{{ item }}</a-link>
					</div>
				</div>
				<div v-else>
					<div>无</div>
				</div>
				
				
			</template>
			<template #is_guoqi="{ record }">
				<!-- 对标题加上 tag -->
				<a-tag color="red" v-if="record.is_guoqi == 1 && record.status == 3">已过期</a-tag>
				<a-tag color="green" v-if="record.is_guoqi == 2 && record.status == 3">生效中</a-tag>
				<a-tag color="gray" v-if="record.status != 3">未生效</a-tag>
			</template>
			<template #status="{ record }">
				<!-- 对标题加上 tag -->
				<a-tag color="gray" v-if="record.status == 1">未提审</a-tag>
				<a-tag color="green" v-if="record.status == 2">审核中</a-tag>
				<a-tag color="blue" v-if="record.status == 3">已通过</a-tag>
				<a-tag color="red" v-if="record.status == 4">已驳回</a-tag>
			</template>
			
			<template #operationBeforeExtend="{ record }">
				<!-- v-if="record.is_guoqi != 2 && record.status != 3" -->
				<a-link @click="handlePeisong(record)" >配送地址</a-link>
				<a-link @click="handleShenPi(record)" v-if="record.status == 1 || record.status == 2" v-auth="['system:userContract:check']" >合同审批</a-link>
				<a-link @click="goodsList(record)" v-auth="['system:userContractGoods:index']">品名明细</a-link>
				<a-link @click="chargingList(record)" v-auth="['system:userContractCharging:index']" >计费配置</a-link>
				<a-link @click="handleYanqi(record)" >修改有效期</a-link>
				<a-link @click="handleDetail(record)" >详情</a-link>
			</template>
		</ma-crud>
		<a-drawer :footer="false" :width="1400" v-model:visible="visibleWare">
			<template #title> 合同仓库 </template>
			<userContractWarehouse
				ref="userContractWarehouseRef"
				:deptIds="deptIds"
        v-if="visibleWare"
			/>
		</a-drawer>

		<a-drawer :footer="false" :width="1400" v-model:visible="visibleGoods">
			<template #title> 品名明细 </template>
			<userContractGoods ref="userContractGoodsRef" />
		</a-drawer>

		<a-drawer :footer="false" :width="1400" v-model:visible="visibleCharging">
			<template #title>{{ deptName }} - {{contractName}} </template>
			<UserContractCharging ref="userContractChargingRef" :inforows="inforow" v-if="visibleCharging"/>
		</a-drawer>
		<!-- 合同延期 -->
		<!-- 预览预计导入的数据 -->
		<a-modal :mask-closable="false"  v-model:visible="showYanqi" title="修改合同有效期" @cancel="handleYanqiCel" :width="1000" ok-text='确认' :on-before-ok="yanqiModalok" >
			<div style="display: flex;align-items: center;margin-bottom: 2%;">
				<div style="width: 100px;">开始时间：</div>
				<a-date-picker
					v-model="yanqiStarttime"
					style="flex:1;"
					format="YYYY-MM-DD"
					@ok="yanqiStartOk"
				/>
			</div>
			<div style="display: flex;align-items: center;margin-bottom: 2%;">
				<div style="width: 100px;">结束时间：</div>
				<a-date-picker
					v-model="yanqiEndtime"
					style="flex:1;"
					format="YYYY-MM-DD"
					@ok="yanqiOk"
				/>
			</div>
			<div style="display: flex;">
				<div style="width: 100px;">延期备注：</div>
				<a-textarea style="flex:1;" v-model="yanqiRemark" placeholder="请输入延期原因" allow-clear/>
			</div>
		</a-modal>

		<!-- 审批 -->
		<a-modal :mask-closable="false"  v-model:visible="shenpiShow" title="审批" :width="1000" ok-text='确认'  :on-before-ok="shenpiModalbeforeok">
			<div class="flex ">
				<div style="width: 120px;">审批结果:</div>
				<a-radio-group v-model="shenpiValue" :options="shenpiList" @change="handleRadioChange">
					<template #label="{ data }">
						<a-tag>{{ data.label }}</a-tag>
					</template>
				</a-radio-group>
			</div>
			<div class="flex " style="margin-top: 2%;">
				<div style="width: 120px;">备注:</div>
				<a-textarea placeholder="请输入备注" allow-clear v-model="remark" class="flex_1" />
			</div>
		</a-modal>
		
		<!-- 配送地址 -->
		<a-drawer :footer="false" :width="1400" v-model:visible="userContractAddressShow">
			<template #title> 合同名称：{{contractName}} </template>
			<userContractAddress ref="userContractAddressRef" />
		</a-drawer>

		<!-- 详情 -->
		<a-modal :mask-closable="false"  v-model:visible="detailShow" title="合同详情" :width="1400" :footer="false">
			<userContractDetail v-if="detailShow" :formData="formData"></userContractDetail>
		</a-modal>

	</div>
</template>
<script setup>
	import { ref, reactive, shallowRef  } from "vue";
	import systemUserContract from "@/api/system/systemUserContract";
	import { Message } from "@arco-design/web-vue";
	import tool from "@/utils/tool";
	import * as common from "@/utils/common";
	import userContractGoods from "@/views/system/userContractGoods/index.vue";
	import UserContractCharging from "@/views/system/userContractCharging/index.vue";
	import userContractWarehouse from "@/views/system/userContractWarehouse/index.vue";
	import userContractAddress from "@/views/system/userContractAddress/index.vue";
	import userContractDetail from "@/views/system/userContract/detail.vue";
	import htgsComponent from "./htgsComponent.vue";
	import { request } from "@/utils/request.js";
	import contractNo from "./contractNo.vue";
	import maps from "@/views/prediction/map/index.vue";
	import dayjs from 'dayjs';
	const crudRef = ref();
	const formData = ref({})
	const detailShow = ref(false)
	const userContractGoodsRef = ref();
	const visibleWare = ref(false);
	const visibleGoods = ref(false);
	const visibleCharging = ref(false);
	const shenpiShow = ref(false)
	const mapShow = ref(false)
	const shenpiItem = ref({})
	const userContractChargingRef = ref();
	const userContractWarehouseRef = ref();
	const showYanqi = ref(false)
	const userContractAddressShow = ref(false)
	const userContractAddressRef = ref(null)
	const contractName = ref('')
	const deptName = ref('')
	const deptIds = ref();
	const inforow = ref()
	const shenpiList = ref([
		{label:'通过',value:'3'},
		{label:'驳回',value:'4'},
	])
	const city = ref()
	const shenpiValue = ref('') 
	const remark = ref('')
	const yanqiRemark = ref('')
	const yanqiStarttime = ref('')
	const yanqiEndtime = ref('')
	const yanqiId = ref('')
	const wareList = (row) => {
		deptIds.value = row;
		visibleWare.value = true;
	};
	const handleYanqi = (e)=>{
		yanqiId.value = e.id
		yanqiStarttime.value = e.start_time
		yanqiEndtime.value = e.end_time
		showYanqi.value = true;
	}
	const handleYanqiCel = ()=>{
		yanqiRemark.value = ''
		yanqiEndtime.value = ''
		yanqiStarttime.value = ''
		showYanqi.value = false;
	}
	const handlechakan = () =>{
		mapShow.value = true
		console.log(mapShow.value)
	}
	const handleDetail = (row)=>{
		formData.value = row
		setTimeout(()=>{
			detailShow.value = true
		},200)
		
	}
	const shenpiModalbeforeok = async () =>{
		if(shenpiValue.value == ''){
			Message.error('请选择审批状态')
			return  false
		}else{
			let res = await systemUserContract.contractCheck({id:shenpiItem.value.id,status:shenpiValue.value ,remark:remark.value})
			if(res.code == 200){
				Message.success('审批成功')
				crudRef.value.refresh()
				return true
			}else{
				Message.error(res.message);
				return false
			}
		}
	}
	
	const handlePeisong = (row)=>{
		contractName.value = row.name
		userContractAddressShow.value = true
		userContractAddressRef.value.open(row)
	}
	const handleShenPi = (row)=>{
		shenpiValue.value = ''
		remark.value = ''
		shenpiShow.value = true
		shenpiItem.value = row
	}
	const yanqiStartOk = (e)=>{
		yanqiStarttime.value = e
	}
	const yanqiOk = (e)=>{
		yanqiEndtime.value = e
	}
	const yanqiModalok = async ()=>{
		let res = await systemUserContract.update(yanqiId.value,{start_time:yanqiStarttime.value,end_time:yanqiEndtime.value,remark:yanqiRemark.value})
		if(res.code == 200){
			res.success && Message.success('修改成功');
			yanqiRemark.value = ''
			yanqiStarttime.value = ''
			yanqiEndtime.value = ''
			showYanqi.value = false;
			crudRef.value.refresh()
			return true
		}else{
			Message.error(res.message);
			return false
		}
	}
	const goodsList = (row) => {
		userContractGoodsRef.value.open(row);
		visibleGoods.value = true;
	};

	const chargingList = (row) => {
		inforow.value = row
		contractName.value = row.name
		deptName.value = row.dept.name
		// userContractChargingRef.value.open(row);
		visibleCharging.value = true;
	};

	const numberOperation = (newValue, id, numberName) => {
		systemUserContract
			.numberOperation({ id, numberName, numberValue: newValue })
			.then((res) => {
				res.success && Message.success(res.message);
			})
			.catch((e) => {
				console.log(e);
			});
	};

	const switchStatus = (statusValue, id, statusName) => {
		systemUserContract
			.changeStatus({ id, statusName, statusValue })
			.then((res) => {
				res.success && Message.success(res.message);
			})
			.catch((e) => {
				console.log(e);
			});
	};
	const contract_nos = ref('')
	const addConShow = ref(1)
	const options = reactive({
		id: "flyos_system_user_contract",
		rowSelection: {
			showCheckedAll: true,
		},
		pk: "id",
		operationColumn: true,
		operationColumnWidth: 230,
		bordered: { cell: true },
		formOption: {
			viewType: "modal",
			width: 800,
		},
		api: systemUserContract.getList,
		recycleApi: systemUserContract.getRecycleList,
		add: {
			show: true,
			api: systemUserContract.save,
			auth: ["system:userContract:save"],
		},
		edit: {
			show: true,
			api: systemUserContract.update,
			auth: ["system:userContract:update"],
		},
		delete: {
			show: true,
			api: systemUserContract.deletes,
			auth: ["system:userContract:delete"],
			realApi: systemUserContract.realDeletes,
			realAuth: ["system:userContract:realDeletes"],
		},
		recovery: {
			show: true,
			api: systemUserContract.recoverys,
			auth: ["system:userContract:recovery"],
		},
		import: {
			show: false,
			url: "system/userContract/import",
			templateUrl: "system/userContract/downloadTemplate",
			auth: ["system:userContract:import"],
		},
		export: {
			show: false,
			url: "system/userContract/export",
			auth: ["system:userContract:export"],
		},
		afterRequest: (params) => {
			// 当前时间戳
			let newData = new Date().getTime()
			params.map((v, i) => {
				if(new Date(v.end_time).getTime() < newData){
					v.is_guoqi = 1
				}else{
					v.is_guoqi = 2
				}
				v.policy = ''
				v.pay_method = v.pay_method.split(',')
			});
		},
		// beforeOpenEdit:(params)=>{
		// 	if(Array.isArray(params.pay_method)){

		// 	}else{
		// 		params.pay_method = params.pay_method.split(',')
		// 	}
		// 	return true
		// },
		beforeEdit:(params)=>{
			params.pay_method = params.pay_method.join(',')
			return true
		},
		beforeAdd:(params)=>{
			params.pay_method = params.pay_method.join(',')
			params.start_time = params.start_time + ' 00:00:00'
			params.end_time = params.end_time + " 23:59:59"
			return true
		},
		beforeOpenAdd:(params)=>{
			request({
				url: '/system/userContract/get_contract_no',
				method: 'get',
			}).then(res=>{
				contract_nos.value  = res.data.contract_no
				addConShow.value = 1
			})
			return true
		},
		beforeOpenEdit:(params)=>{
			contract_nos.value = ''
			addConShow.value = 2
			return true
		}
	});

	const columns = reactive([
		{
			title: "ID",
			dataIndex: "id",
			formType: "input",
			addDisplay: false,
			align: "center",
			editDisplay: false,
			hide: true,
			commonRules: {
				required: true,
				message: "请输入ID",
			},
		},
		{
			title: "合同公司",
			dataIndex: "dept_id",
			align: "center",
			formType: "component",
			component: shallowRef(htgsComponent),
			// width:180,
			hide: true,
			search: false,
			commonRules: {
				required: true,
				message: "请选择合同公司",
			},
		},
		{
			title: "合同公司",
			dataIndex: "dept_id",
			align: "center",
			formType: "select",
			addDisplay:false,
			editDisplay:false,
			width:180,
			search: true,
			dict: {
				// 远程通用接口请求，新版代码生成都有一个 remote 接口
				remote: "system/dept/remote",
				// 指定组件接收的props
				props: { label: "name", value: "id" },
				// 开启分页
				openPage: false,
				// 远程请求配置项
				remoteOption: {
					// 按用户名排序
					sort: { id: "desc" }, // 如果不指定排序方式，默认为正序排序
					// 设置查询的字段
					select: ["id", "name"],
					// 设置数据过滤
					filter: {
						type: ["=", 2],
						status: ['=',1]
					},
					// 关联模型
					relations: [],
				},
			},
			commonRules: {
				required: true,
				message: "请选择合同公司",
			},
		},
		
		
		
		{
			
			dataIndex: "charge_type",
			formType: "radio",
			title: "计费政策",
			search: true,
			align: "center",
			control: (val) => {
				if (val == 1) {
					if(addConShow.value == 1){
						crudRef.value.crudFormRef.form.contract_no = contract_nos.value
					}
					
					return {
						template_id: { display: true },
					}
				}
				if (val == 2) {
					return {
						template_id: { display: false },
					}
				}
			},
			dict: {
				data()
				{
				return [
					{label: "公示价格", value: 1},
					{label: "一企一策", value: 2},
				]
				},
				translation: true
			},
			commonRules: {
				required: true,
				message: "请选择计费政策"
			},
			
		},
		{
			title: "计费模版",
			dataIndex: "template_id",
			align: "center",
			formType: "select",
			width:180,
			addDisplay:false,
			editDisplay:false,
			hide:true,
			dict: {
				// 远程通用接口请求，新版代码生成都有一个 remote 接口
				url: "system/template/index",
				method:'GET',
				// 指定组件接收的props
				props: { label: "name", value: "id" },
				// 开启分页
				openPage: false,
				// 远程请求配置项
				remoteOption: {
					// 设置查询的字段
					select: ["id", "name"],
					// 关联模型
					relations: [],
				},
			},
			commonRules: {
				required: true,
				message: "请选择计费模版",
			},
		},
		{
			title: "合同名称",
			dataIndex: "name",
			formType: "input",
			width:180,
			align: "center",
			search: true,
			commonRules: {
				required: true,
				message: "请输入合同名称",
			},
		},
		
		{
			title: "合同号",
			dataIndex: "contract_no",
			formType: "component",
			align: "center",
			sortable:{
				sortDirections: ['ascend', 'descend'], sorter: true
			},
			width:180,
			search: true,
			component: shallowRef(contractNo)
		},
		{ title: '免费堆放天数', dataIndex: 'zc_day',  align:'center',width: 120,formType:'input' },
    // {
    //   dataIndex: "is_taoxiang",
    //   formType: "radio",
    //   title: "是否掏箱",
	//   align: "center",
	//   width:100,
    //   addDefaultValue: 0,
    //   dict: {
    //     data()
    //     {
    //       return [
    //         {label: "是", value: 1},
    //         {label: "否", value: 0},
    //       ]
    //     },
    //     translation: true
    //   },
    //   commonRules: {
    //     required: true,
    //     message: "请选择是否掏箱"
    //   }
    // },
		{
			title: "合同附件",
			dataIndex: "annex",
			align: "center",
			formType: "upload",
			type: "file",
			multiple: true,
			returnType: "url",
		},
		{
			title: "开始时间",
			dataIndex: "start_time",
			align: "center",
			formType: "date",
			search: false,
			addDisabled:false,
			editDisabled:true,
			commonRules: {
				required: true,
				message: "请选择开始时间"
			},
		},
		{
			title: "结束时间",
			dataIndex: "end_time",
			align: "center",
			formType: "date",
			addDisabled:false,
			editDisabled:true,
			search: false,
			disabledDate:(current) => {
				// return true
				let newData = new Date(current).getTime()    //  每一天的时间戳
				let newDatas = new Date(crudRef.value.crudFormRef.form.start_time).getTime()    //  开始时间戳
				if(newData < newDatas){
					return true
				}else{
					return false
				}
				
				
			},
			commonRules: {
				required: true,
				message: "请选择结束时间"
			}
		},
		{
			title: "合同开始时间",
			dataIndex: "start_time",
			align: "center",
			formType: "range",
			search: true,
			addDisplay:false,
			editDisplay:false,
			showTime: true,
			hide:true,
			commonRules: {
				required: true,
				message: "请选择开始时间"
			},
		},
		{
			title: "合同结束时间",
			dataIndex: "end_time",
			align: "center",
			formType: "range",
			addDisplay:false,
			editDisplay:false,
			hide:true,
			search: true,
			showTime: true,
			disabledDate:(current) => {
				// return true

				let newData = new Date(current).getTime()    //  每一天的时间戳
				let newDatas = new Date(crudRef.value.crudFormRef.form.start_time).getTime()    //  开始时间戳
				if(newData < newDatas){
					return true
				}else{
					return false
				}
				
				
			},
			commonRules: {
				required: true,
				message: "请选择结束时间"
			}
		},
		{
			title: "审批状态",
			dataIndex: "status",
			align: "center",
			formType: "select",
			addDefaultValue: 1,
			addDisplay: false,
			editDisabled:true,
			search: true,
			commonRules: {
				required: true,
				message: "请输入审批状态",
			},
			dict: {
				name: "contract_status",
				props: {
					label: "title",
					value: "key",
				},
				translation: true,
			},
		},
    {
      title: "结算方式",
      dataIndex: "pay_method",
      align: "center",
      formType: "checkbox",
	  width:180,
      addDefaultValue: 1,
    //   search: true,
      commonRules: {
        required: true,
        message: "请选择支付方式",
      },
      dict: {
        data: [
          {label: '预付', value: '1'},
          {label: '周期结算', value: '2'},
          {label: '现结', value: '3'},
        ],
        translation: true,
      },
    },
	
	{
      title: "合同状态",
      dataIndex: "is_guoqi",
      align: "center",
      formType: "radio",
      addDefaultValue: 1,
      search: true,
	  addDisplay: false,
	  editDisplay: false,
	  dict: {
        data: [
          {label: '已过期', value: 1},
          {label: '生效中', value: 2},
          {label: '未生效', value: 3},
        ],
        translation: true,
      },
      
    },
	
		{
			title: "合同创建时间",
			dataIndex: "created_at",
			formType: "range",
			align: "center",
			sortable:{
				sortDirections: ['ascend', 'descend'], sorter: true
			},
			search: true,
			addDisplay: false,
			editDisplay: false,
			showTime: true,
		},
		{
			title: "备注",
			dataIndex: "remark",
			formType: "input",
			align: "center",
			addDisplay: false,
			editDisplay: false,
		},
	]);
</script>
<script>
	export default { name: "system:userContract" };
</script>
